<template>
    <view class="content">

        <view class="dropdown-container" :style="dropDownShow ? '' :'overflow:hidden'">
            <u-dropdown active-color="#3cc51f" @open="open" @close="close">
                <u-dropdown-item height="700" v-model="selectedType" title="类型" :options="typeList"  @change="typeDropDownChange"></u-dropdown-item>
                <u-dropdown-item v-model="selectedHot" title="热门" :options="hotList"  @change="hotDropDownChange"></u-dropdown-item>
            </u-dropdown>
        </view>
        <view style="height: 80rpx"></view>

        <!-- 商店列表 -->
        <view class='shop-list'>

            <s-merchant-item v-for="(item,index) of merchantList" :key='index'
                             :merchant-item="item"
                             @click="toShopDetail(item.merchant_id,item.name)"></s-merchant-item>
<!--            <view class="list-item" v-for="(item,index) of merchantList" :key='index' @click='toShopDetail(item.merchant_id,item.name)'>
                <view style="display: flex;">
                    <view class='shop-img'>
                        <image mode="aspectFill" :src="item.logo_img_url"></image>
                    </view>
                    <view class='shop-info'>
                        <view class="shop-name"><text>{{ item.name }}</text></view>
                        <view class='rate-sales'>
                            <view>
                                &lt;!&ndash;  评分组件 &ndash;&gt;
                                <u-rate inactive-color='#ccc' :count="count" v-model="value" size="24" disabled></u-rate>
                                &lt;!&ndash; <text class='sales_volume'>月销<text style='font-size: 24rpx;'>999+</text></text> &ndash;&gt;
                            </view>
                            <view>
                                <text class='shop-site'>{{ item.address }}</text>
                                <text class='shop-distance'>{{ item.distance }}</text>
                            </view>
                        </view>
                    </view>
                </view>
                 <view class="merchant_recommend">商家推荐: 香格里拉寻味火锅店优质商家, 价格优惠、人气爆棚</view>
            </view>-->

<!--			<view class="list-item" v-for="(item,index) of merchantList" :key='index' @click='toShopDetail(item.merchant_id,item.name)'>-->
<!--			    <view style="display: flex;">-->
<!--			        <view class='shop-img'>-->
<!--			            <image mode="aspectFill" :src="item.logo_img_url"></image>-->
<!--			        </view>-->
<!--			        <view class='shop-info'>-->
<!--			            <view class="shop-name"><text>{{ item.name }}</text></view>-->
<!--			            <view class='rate-sales'>-->
<!--			                <view>-->
<!--			                    &lt;!&ndash;  评分组件 &ndash;&gt;-->
<!--			                    <u-rate inactive-color='#ccc' :count="count" v-model="value" size="24" disabled></u-rate>-->
<!--			                    &lt;!&ndash; <text class='sales_volume'>月销<text style='font-size: 24rpx;'>999+</text></text> &ndash;&gt;-->
<!--			                </view>-->
<!--			                <view>-->
<!--			                    <text class='shop-site'>{{ item.address }}</text>-->
<!--			                    <text class='shop-distance'>{{ item.distance }}</text>-->
<!--			                </view>-->
<!--			            </view>-->
<!--			        </view>-->
<!--			    </view>-->
<!--			    &lt;!&ndash; <view class="merchant_recommend">商家推荐: 香格里拉寻味火锅店优质商家, 价格优惠、人气爆棚</view> &ndash;&gt;-->
<!--			</view>-->

            <view style="padding: 30rpx 0">
                <u-loadmore :status="loadingStatus" :loading-text="loadText" margin-bottom="22" />
            </view>

		</view>
    </view>
</template>
<script>
import merchantItem from '@/components/merchant-item/index.vue'
export default {
    components: {
      's-merchant-item': merchantItem
    },
    data() {
        return {
            merchant: '',

            count: 5, // 一共有5颗星星
            value: 4,

            errImgUrl: this.$errorImgUrl,//找不到图片的URL
            total: '',
            page: 1,
            loadingStatus: 'nomore',
            loadText: {
                loadmore: '轻轻上拉',
                loading: '努力加载中',
                nomore: '没有更多了'
            },
            merchantList: [], // 店铺列表
            couponList: [],
            userToken: '',
            nickname: '',
            photo_url: '',
            isOnLoad: false, //判断onLoad是否执完行了

            isGetLocation: true,
            layerModel: false,
            area_id:0,
            typeList: [{label:"全部",value:0}],
            selectedType: '',
            typeId:0,
            hotList:  [{label: '是', value: 1},{label: '否', value: 0}],
            selectedHot: '',
            dropDownShow: false
        }
    },

    onShow(){

    },

	onLoad() {
        this.initPageData()
    },

    onPullDownRefresh() {
        this.merchantList = [];
        this.page=1;
        this.getMerchantList()
    },

	onReachBottom() {
		if (this.loadingStatus === "loading" || this.loadingStatus === "nomore") {
			return;
		}
		this.page ++;
		this.loadingStatus = "loading";
		this.getMerchantList();

	},

    methods: {

        initPageData() {
            this.merchantList = [];
            this.page=1;
            this.getUserInfos();
            this.getLocationInfo();
            this.getShopsClassifyRequest();
        },

		// 进入店铺详情页面
        toShopDetail(id,name) {
            wx.navigateTo({
                url: `/pages/shopDetail/shopDetail?merchant_id=${id}&name=${name}`
            })
        },

        typeDropDownChange(value) {
            this.updateMerchantData(value)
        },

        hotDropDownChange(value) {
            this.updateMerchantData()
        },

        updateMerchantData(value) {
            this.typeId = value
            this.page = 1
            this.merchantList = []
            this.getMerchantList()
        },

      async getShopsClassifyRequest(){
        const res = await this.$api.getShopsClassify({}, this.$baseUrl);

        if (res.data.level === "success") {
          let datas = res.data.data
          console.log("datas",datas)
          for (var i=0;i<datas.length;i++){
            let a = {label:datas[i].name,value:datas[i].id};
            this.typeList.push(a);
          }
          // console.log("typeList",this.typeList)
        }
      },

        // 获取商店列表
        async getMerchantList() {
            // this.merchantList
            // this.merchantList = [];
            const lat = wx.getStorageSync("latitude")
            const lng = wx.getStorageSync("longitude")
			const page = this.page
            let area_id = 0;

            this.loadingStatus = "loading";
            const userToken=wx.getStorageSync('userToken');
            this.area_id=wx.getStorageSync('area_id');
            if(this.area_id){
                area_id = this.area_id
            }
            let classify_id = this.typeId

            const res = await this.$api.getMerchantList({lat,lng,page,area_id:area_id,classify_id:classify_id}, this.$baseUrl);

            if (res.data.level === "success") {
                this.merchantList.push(...res.data.data);
                if (this.merchantList.length == res.data.page_info.total) {
                    this.loadingStatus = "nomore";
                } else {
                    this.loadingStatus = "loadmore";
                }
                wx.stopPullDownRefresh()
            } else {
                wx.showToast({
                    title: res.data.message,
                    icon: "none",
                    duration: 1500
                })
            }
        },

        //微信授权
        async bindGetUserInfo(){
            var _this=this;
            uni.login({
                success: res =>{
                    let code = res.code;
                    uni.getUserInfo({
                        success: async res => {
                            wx.showLoading({
                                title: '正在登录'
                            })
                            let params = {
                                raw_data:res.rawData,
                                signature:res.signature,
                                code:code
                            }
                            const result = await _this.$api.wxAppLogin(params,this.$baseUrl);
                            if (result.data.level == 'success'){
                                uni.setStorageSync('userToken',result.data.data);
                                _this.getUserInfos()
                                wx.hideLoading();
                                this.$currency.showToast('登录成功','success')
                            } else{
                                wx.hideLoading();
                                wx.showToast({
                                    title: result.data.message,
                                    icon: "none",
                                    duration: 1500
                                })
                            }
                        },
                        fail: (res) => {
                            wx.hideLoading()
                        }
                    })
                }
            })
        },

        //获取个人信息
        async getUserInfos(){
            let userToken=wx.getStorageSync('userToken');
            if(userToken){
                const res=await this.$api.getUserInfos({user_token:userToken},this.$baseUrl);
                if(res.data.level=='success'){
                    let userInfo = res.data.data
                    uni.setStorageSync('user_id',userInfo.id);
                    uni.setStorageSync('wx_openid',userInfo.wx_openid);
                    uni.setStorageSync('photo_url',userInfo.user_info.photo_url)
                    uni.setStorageSync('nickname',userInfo.user_info.nickname)

                    this.userToken = userToken
                    this.merchant = wx.getStorageSync('merchant')
                    //udesk获取用户信息
                    if(userInfo != ""){
                        this.nickname = userInfo.user_info.nickname;
                        this.photo_url = userInfo.user_info.photo_url;
                    }
                }
            }

        },

        contactCallBall(e) {
            console.log(e)
            if(e.detail.path){
                this.$currency.navigateTo('/pages/udeskCart/index?key='+e.detail.query.key)
            }
        },

        // 通过微信获取经纬度
        getLocationInfo() {
            wx.getLocation({
                type: 'gcj02',
                success: res => {
                    this.isGetLocation = true;
                    wx.setStorageSync("latitude", res.latitude)
                    wx.setStorageSync("longitude", res.longitude)
                    console.log('获取经纬度',res.latitude,res.longitude)
                    this.getMerchantList()
                },
                fail: err => {
                    console.log('看看错误',err)
                    this.isGetLocation = false;
                    wx.getSetting({
                        success: res => {
                            if (!res.authSetting["scope.userLocation"]) {
                                // 打开提示框, 提示前往设置页面
                                console.log(2);
                                this.layerModel = true;
                            } else {
                                console.log(3);
                                wx.showToast({
                                    title: "请检查手机位置服务是否打开",
                                    icon: "none"
                                });
                            }
                        }
                    })
                },
            })
        },

        open(){
            this.dropDownShow = true
        },

        close(){
            this.dropDownShow = false
        }


    }
}
</script>

<style lang="scss">
    @import "uview-ui/index.scss";
</style>

<style scoped lang="scss">
    @import "../../common/css/mixin";

    .dropdown-container {
        position: fixed;
        z-index: 88;
        width: 100vw;
        background-color: #ffffff;
        height: 80rpx;
    }

    .shop-list {
        box-sizing: border-box;
        width: 100vw;

        .list-item {
            box-sizing: border-box;
            width: 710rpx;
            height: 215rpx;
            padding: 18rpx;
			margin-bottom: 20rpx;
            background-color: #FFF;

            .shop-img {
                width: 110rpx;
                height: 110rpx;
                image {
                    width: 100%;
                    height: 100%;
                }
            }

            .shop-info {
                width: calc(100% - 110rpx);
                padding-left: 18rpx;
                .shop-name {
                    font-size: 36rpx;
                    font-weight: 500;
                    color: #333333;
                }

                .rate-sales {
                    display: flex;
                    justify-content: space-between;
                    height: 80rpx;
                    line-height: 80rpx;
                    font-size: 28rpx;
                    font-weight: 400;
                    color: #333333;
                    .sales_volume { // 月销
                        margin-left: 20rpx;
                    }
                    .shop-site {	// 地址
                        display: inline-block;
                        max-width: 240rpx;
                        margin-right: 14rpx;
                        font-size: 24rpx;
                        white-space: nowrap;
                        text-overflow: ellipsis;
                        overflow: hidden;
                    }
                    .shop-distance{
                        display: inline-block;
                        vertical-align: top;
                        font-size: 24rpx;
                    } // 距离
                }
            }

            .merchant_recommend {
                font-size: 24rpx;
                font-weight: 400;
                color: #333333;
                white-space: nowrap;
                text-overflow: ellipsis;
                overflow: hidden;
            }
        }
    }
</style>
